package com.authine.cloudpivot.ext.utils;

import cn.hutool.core.util.StrUtil;
import com.authine.cloudpivot.engine.api.utils.FileHelper;
import org.apache.poi.ss.usermodel.*;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author hxd
 * @Date 2022/3/30 10:02
 * @Description
 **/
public class ExcelUtils {


    /**
     *  解析excel
     * @param inp
     * @param fileName
     * @param colCode
     * @return
     * @throws Exception
     */
    public static List<Map<String,Object>> excelParse(InputStream inp,String fileName,List<String> colCode) throws Exception {


        String fileExtension = fileName.substring(fileName.lastIndexOf(".")+1);

        if (fileName.contains(".") && !org.apache.commons.lang3.StringUtils.equalsAny(fileExtension, new CharSequence[]{"xls", "xlsx"})){
            throw new RuntimeException("文件格式错误,只支持xlsx或xls格式文件");
        }

        Workbook wb = WorkbookFactory.create( inp);

        Sheet sheet = wb.getSheetAt(0);
        Row firstRow = sheet.getRow(0);

        List<String> colName = new ArrayList<>();
        for (int i = 0; i < colCode.size(); i++) {
            colName.add(FileHelper.getStringCellValue(firstRow.getCell(i)));
        }

        int lastRowNum = sheet.getLastRowNum();
        //取出导入数据
        List<Map<String, Object>> list = new ArrayList<>();
        for (int i = 1; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);

            if (row == null) {
                throw new RuntimeException(StrUtil.format("第({})行不能为空,请删除空行",i+1));
            }

            Map<String, Object> map = new HashMap<>();
            for (int j = 0; j < colCode.size(); j++) {
                Cell cell = row.getCell(j);
                String value ;
                if (cell == null || org.apache.commons.lang3.StringUtils.isEmpty(value=FileHelper.getStringCellValue(cell))){
                    throw new RuntimeException(StrUtil.format("第({})行({})列不能为空",i+1,colName.get(j)));
                }

                map.put(colCode.get(j), value);
            }

            list.add(map);
        }

        return list;

    }


}
